package com.heima.Serivce.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.Common.NewImage;
import com.heima.Config.ThreadUtil;
import com.heima.Mapper.WemediamaterialMapper;
import com.heima.Mapper.WemediamaterialNewMapper;
import com.heima.Mapper.WemediamaterialNew_maMapper;
import com.heima.Serivce.ArticleCilent;
import com.heima.Serivce.WemediaMQ;
import com.heima.Serivce.WemediaNewScan;
import com.heima.Serivce.WemediaSchedlue;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.dtos.WmNewsPageReqDto;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

import static com.heima.model.common.contans.WemediaConstants.*;

@Service
@Transactional
public class WemediamaterialNewService implements com.heima.Serivce.WemediamaterialNewService {
    @Autowired
    WemediamaterialNewMapper wemediamaterialNewMapper;

    @Autowired
    WemediamaterialNew_maMapper wemediamaterialNew_maMapper;

    @Autowired
    WemediamaterialMapper wemediamaterialMapper;

    //    文章审核类
    @Autowired
    WemediaNewScan wemediaNewScan;


    @Qualifier("com.heima.Serivce.ArticleCilent")
    @Autowired
    ArticleCilent articleCilent;

    @Autowired
    WemediaSchedlue wemediaSchedlue;

    @Autowired
    WemediaMQ wemediaMQ;

//        查询文章
    @Override
    @Transactional
    public ResponseResult GetNewList(WmNewsPageReqDto wmNewsPageReqDto) {
        QueryWrapper<WmNews> wrapper = new QueryWrapper<>();
//        添加文章状态
        if (wmNewsPageReqDto.getStatus() != null)
            wrapper.eq("status", wmNewsPageReqDto.getStatus());

//        添加文章频道
        if (wmNewsPageReqDto.getChannelId() != null)
            wrapper.eq("channel_id", wmNewsPageReqDto.getChannelId());

//        添加查询时间段
        if (wmNewsPageReqDto.getBeginPubDate() != null && wmNewsPageReqDto.getEndPubDate() != null)
            wrapper.between("submited_time",
                    wmNewsPageReqDto.getBeginPubDate(), wmNewsPageReqDto.getEndPubDate());

//        添加查询关键字
        if (wmNewsPageReqDto.getKeyword() != null)
            wrapper.like("title", wmNewsPageReqDto.getKeyword());

//        添加查询用户id
        WmUser wmUser = ThreadUtil.threadLocal.get();
        if(wmUser!=null)
        wrapper.eq("user_id", wmUser.getId());

//        添加查询分页条件
        Page<WmNews> page = new Page<>(wmNewsPageReqDto.getPage(), wmNewsPageReqDto.getSize());
        Page<WmNews> wmNewsPage = wemediamaterialNewMapper.selectPage(page, wrapper);

        return ResponseResult.okResult(wmNewsPage.getRecords());
    }

//    上传or下架
    @Override
    @GlobalTransactional
    public ResponseResult DownOrUp(Integer id, int enable) {
//        查询文章是否存在
        WmNews wmNews = wemediamaterialNewMapper.selectById(id);
        int num = 0;
        if (wmNews != null) {
//            修改文章状态
            wmNews.setStatus((short) enable);
            wemediamaterialNewMapper.updateById(wmNews);
//              把相关App端的文章id传给App
            Boolean IsDown=true;
            if(enable==1)
                IsDown=false;
            wemediaMQ.pushmassge(wmNews.getArticleId(),IsDown);
        }
        return ResponseResult.okResult(num);
    }


    //    发布文章
    @Override
    @Transactional
    public ResponseResult Submit(WmNewsDto wmNewsDto) {

        ResponseResult responseResult=new ResponseResult();
        responseResult.ok("发布成功");

//        判断文章内容是否有效
        if (wmNewsDto.getTitle() == null || wmNewsDto.getContent() == null)
            return ResponseResult.errorResult(501, "文章标题或者内容不能为空");

        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(wmNewsDto, wmNews);
        wmNews.setStatus((short)3);
        Integer id = ThreadUtil.threadLocal.get().getId();
        wmNews.setUserId(id);
//        判断是否存在文章
        QueryWrapper<WmNews> existwrapper = new QueryWrapper<>();
//        新文章是没有id传进来的
        if (wmNews.getId() == null)
            existwrapper.eq("title", wmNewsDto.getTitle())
                    .eq("user_id", ThreadUtil.threadLocal.get().getId());
//        旧文章有id
        else
            existwrapper.eq("id", wmNews.getId());
        WmNews existnew = wemediamaterialNewMapper.selectOne(existwrapper);
//            封面属性拷贝
        String images = StringUtils.join(wmNewsDto.getImages(), ",");
        wmNews.setImages(images);
        if(wmNews.getPublishTime()==null)
        {
            wmNews.setPublishTime(new Date());
        }
        if (existnew == null) {
//            添加文章
            Integer newId = InsertArticle(wmNews);
//            判断是否是草稿
            if (wmNewsDto.getStatus() != (short) 0) {
//            添加素材和文章的关联
                AddNew_macontact(wmNewsDto, newId);
                wmNews.setId(newId);
////                文章审核
//                responseResult=wemediaNewScan.NewSCan(wmNews);
//                提交任务
                wemediaSchedlue.AddTask(wmNews.getId(),wmNews.getPublishTime());

            }
        } else {
//            不是新文章
//            修改文章
            QueryWrapper<WmNews> newsQueryWrapper=new QueryWrapper<>();
            newsQueryWrapper.eq("title", wmNewsDto.getTitle())
                    .eq("user_id", ThreadUtil.threadLocal.get().getId());
            WmNews one = wemediamaterialNewMapper.selectOne(newsQueryWrapper);
            QueryWrapper<WmNewsMaterial> wrapper = new QueryWrapper<>();
//            删除素材和文章的关联
            if(one.getType()!=(short)0)
            {
                wrapper.eq("news_id", one.getId());
                wemediamaterialNew_maMapper.delete(wrapper);
            }
//            提交文章
            Integer NewId = UpdateArticle(wmNews);
//            是草稿，直接保存
            if (wmNewsDto.getStatus() != (short) 0) {
//            不是草稿，确认要发布文章
//            添加素材和文章的关联
                AddNew_macontact(wmNewsDto, NewId);
////             文章审核
//                responseResult=wemediaNewScan.NewSCan(wmNews);
//                提交任务
                wemediaSchedlue.AddTask(wmNews.getId(),wmNews.getPublishTime());
            }
        }
        return responseResult;
    }

    //    根据id查询文章内容
    @Override
    public ResponseResult SelectById(Integer id) {

        WmNews wmNews = wemediamaterialNewMapper.selectById(id);
        return ResponseResult.okResult(wmNews);
    }

    @Override
    @Transactional
    public ResponseResult Delete(Integer id) {
//        删除文章
        wemediamaterialNewMapper.deleteById(id);
        QueryWrapper<WmNewsMaterial> wrapper = new QueryWrapper<>();
        wrapper.eq("news_id", id);
//        删除文章与素材的联系
        wemediamaterialNew_maMapper.delete(wrapper);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult Updata(WmNews wmNews) {
        if(wmNews==null)
            return ResponseResult.errorResult(404,"数据不能为空");
        int i = wemediamaterialNewMapper.updateById(wmNews);
        return ResponseResult.okResult(i);
    }


    //    添加文章和素材的联系表
    @Transactional
    public List<WmNewsMaterial> AddNew_macontact(WmNewsDto wmNewsDto, Integer NewId) {
        List<WmNewsMaterial> arr = new ArrayList<>();
//        images为图片地址
        List<NewImage> images = new ArrayList<>();
//        封面自动类型逻辑处理
        if (wmNewsDto.getType() == (short) -1) {
            wmNewsDto = CoverType(wmNewsDto);
        }
        for (String image : wmNewsDto.getImages()) {
//            添加封面图片联系
            NewImage newImage = new NewImage();
            newImage.setUrl(image);
            newImage.setType((short) 1);
            images.add(newImage);
        }
//        获取文章内容里的图片
        images.addAll(GetContenImgaes(wmNewsDto.getContent()));
//        查寻刚添加的文章
//        wemediamaterialNewMapper.selectById(NewId);
//        添加封面图片联系
        for (NewImage newImage : images) {
//            查询图片id
            WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
            QueryWrapper<WmMaterial> imagewrapper = new QueryWrapper<>();
            imagewrapper.eq("url", newImage.getUrl());
            wmNewsMaterial.setMaterialId(
                    wemediamaterialMapper.selectOne(imagewrapper).getId());
            wmNewsMaterial.setNewsId(NewId);
            wmNewsMaterial.setType(newImage.getType());
            arr.add(wmNewsMaterial);
        }
//        添加内容图片联系
        if(arr!=null&&arr.size()!=0)
        {
            int num = wemediamaterialNew_maMapper.Save(arr);
        }
        return arr;
    }

//    添加文章

    @Transactional
    public Integer InsertArticle(WmNews wmNews) {
        Integer userId = ThreadUtil.threadLocal.get().getId();

        wmNews.setUserId(userId);
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wemediamaterialNewMapper.insert(wmNews);

        QueryWrapper<WmNews> wrapper = new QueryWrapper<>();
        wrapper.eq("title", wmNews.getTitle()).eq("user_id", userId);
        WmNews Tempwmnew = wemediamaterialNewMapper.selectOne(wrapper);
        return Tempwmnew.getId();
    }

    //    修改文章
    private Integer UpdateArticle(WmNews wmNews) {
        wemediamaterialNewMapper.updateById(wmNews);
        return wmNews.getId();
    }

    //    获取文章内容里的图片
    private List<NewImage> GetContenImgaes(String Content) {
        List<NewImage> contentarr = new ArrayList<>();
        List<Map> jsonmap = JSON.parseArray(Content, Map.class);
        for (Map map : jsonmap) {
            if (map.get("type").equals("image")) {
                NewImage newImage = new NewImage();
                newImage.setUrl((String) map.get("value"));
                newImage.setType((short) 0);
                contentarr.add(newImage);
            }
        }

        return contentarr;
    }

    //    封面自动类型逻辑处理
    private WmNewsDto CoverType(WmNewsDto wmNewsDto) {
//            封面类型为自动
        List<NewImage> covermap = GetContenImgaes(wmNewsDto.getContent());
        int mapsize = covermap.size();
        if (mapsize < 1)
//                无图
            wmNewsDto.setType(WM_NEWS_NONE_IMAGE);
        if (mapsize > 1 & mapsize < 3) {
//                单图 封面默认为内容里的第一张图
            wmNewsDto.setType(WM_NEWS_SINGLE_IMAGE);
            List<String> arr = new ArrayList<>();
            arr.add(covermap.get(0).getUrl());
            wmNewsDto.setImages(arr);
        }
        if (mapsize >= 3) {
//            三图 默认为内容的前三副图
            wmNewsDto.setType(WM_NEWS_MANY_IMAGE);
            List<String> arr = new ArrayList<>();
            arr.add(covermap.get(0).getUrl());
            arr.add(covermap.get(1).getUrl());
            arr.add(covermap.get(2).getUrl());
            wmNewsDto.setImages(arr);
        }
        return wmNewsDto;
    }

}
